#include "./draw_task.h"
#include "../driver/parts.h"
#include "../driver/sensor.h"
#include "../utils/progress.h"
#include "../service/config.h"

namespace task {

using namespace driver;
using namespace utils;
using namespace service;

void DrawTask::run() {

    for (;;) {
        switch (m_state) {
            case State::WORK: do_work(); break;
            case State::IDLE: do_idle(); break;
            case State::STOP: do_stop(); break;
            case State::TIMEOUT: do_timeout(); break;
            case State::DRAW_OUTLET: do_draw_outlet(); break;
        }
    }
}

bool DrawTask::await(uint32_t timeout) {
    return m_mq.poll(m_state, timeout) == osOK;
}

void DrawTask::do_work() {
    Progress prog;
    for (;;) {
        if (sensor->is_steam_high()) {
            m_state = State::IDLE;
            break;
        }

        if (sensor->is_leak()) {
            m_state = State::DRAW_OUTLET;
            break;
        }

        parts->valve_open(1);
        parts->steam_pump_open();

        if (prog.is_after(config->draw_timeout)) {
            m_state = State::TIMEOUT;
            break;
        }

        if (await(1000)) {
            break;
        }
    }
    parts->valve_close(1);
    parts->steam_pump_close();
}

void DrawTask::do_idle() {

    for (;;) {
        if (!sensor->is_steam_high()) {
            m_state = State::WORK;
            break;
        }

        if (sensor->is_leak()) {
            m_state = State::DRAW_OUTLET;
            break;
        }

        if (await(1000)) {
            break;
        }
    }
}

void DrawTask::do_draw_outlet() {
    parts->outlet_pump_open();
    for (;;) {
        if (!sensor->is_leak()) {
            m_state = State::IDLE;
            break;
        }

        if (await(1000)) {
            break;
        }
    }
    parts->outlet_pump_close();
}

void DrawTask::do_stop() {
    parts->valve_close(1);
    parts->steam_pump_close();
    await();
}

void DrawTask::do_timeout() {
    parts->valve_close(1);
    parts->steam_pump_close();
    await();
}

}
